package com.example.peibei.ui.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.dingtao.common.bean.HomeBannerCate;
import com.dingtao.common.bean.WeekTimeBean;
import com.dingtao.common.core.DataCall;
import com.dingtao.common.core.WDActivity;
import com.dingtao.common.core.exception.ApiException;
import com.dingtao.common.util.SPUtils;
import com.dingtao.common.util.UIUtils;
import com.dingtao.common.util.recyclerview.SpacingItemDecoration;
import com.example.peibei.R;
import com.example.peibei.base.Constant;
import com.example.peibei.base.SpConstant;
import com.example.peibei.service.presenter.HomeBannerCatePresenter;
import com.example.peibei.service.presenter.SendOrderPresenter;
import com.example.peibei.ui.adapter.WeekTimeAdapter;
import com.example.peibei.ui.fragment.HomeFragment;
import com.linxiao.framework.dialog.BottomDialog;
import com.zhouwei.mzbanner.holder.MZHolderCreator;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import cn.addapp.pickers.listeners.OnItemPickListener;
import cn.addapp.pickers.listeners.OnMoreItemPickListener;
import cn.addapp.pickers.listeners.OnMoreWheelListener;
import cn.addapp.pickers.listeners.OnSingleWheelListener;
import cn.addapp.pickers.picker.LinkagePicker;
import cn.addapp.pickers.picker.SinglePicker;
import cn.addapp.pickers.util.DateUtils;

public class SendOrderNextActivity extends WDActivity implements SeekBar.OnSeekBarChangeListener {
    @BindView(R.id.rb_set_age)
    RadioButton rb_set_age;
    @BindView(R.id.tv_mix)
    TextView tv_mix;
    @BindView(R.id.tv_max)
    TextView tv_max;
    @BindView(R.id.seek_bar)
    SeekBar seek_bar;
    @BindView(R.id.rl_edit_money)
    RelativeLayout rl_edit_money;
    @BindView(R.id.et_money)
    EditText et_money;
    @BindView(R.id.rl_edit_money_right)
    RelativeLayout rl_edit_money_right;
    @BindView(R.id.rl_choose_skill)
    RelativeLayout rl_choose_skill;
    @BindView(R.id.tv_skill)
    TextView tv_skill;
    @BindView(R.id.rv_week_time)
    RecyclerView rv_week_time;
    @BindView(R.id.ll_add_week)
    LinearLayout ll_add_week;
    @BindView(R.id.rg_gender)
    RadioGroup rg_gender;

    private String content;
    private String filePath;
    private String skill;
    private String startTime = "00:00";
    private String endTime = "24:00";
    private int categoryId;
    private int mixAge = 18;
    private int maxAge = 60;
    private int chooseAge;
    private int week = 1;
    private String weekName = "周一";
    private HomeBannerCatePresenter homeBannerCatePresenter;
    List<HomeBannerCate.CategoryDTO> cates = new ArrayList<>();
    List<WeekTimeBean> weekTimes = new ArrayList<>();
    List<WeekTimeBean> weeks = new ArrayList<>();
    private WeekTimeAdapter weekTimeAdapter;
    private SPUtils spUtils;
    private String token;
    private String cityName;
    private String cityCode;
    private SendOrderPresenter sendOrderPresenter;
    private String gender = "0";
    private String timeLimit = "1_00:00-24:00";

    @Override
    protected int getLayoutId() {
        return R.layout.activity_send_order_next;
    }

    @SuppressLint("SetTextI18n")
    @Override
    protected void initView() {
        Intent intent = getIntent();
        Bundle bundle = intent.getExtras();
        content = bundle.getString("content");
        filePath = bundle.getString("filePath");
        spUtils = new SPUtils(this, SpConstant.USER_TOKEN);
        token = spUtils.getString(SpConstant.USER_TOKEN);
        cityName = spUtils.getString(SpConstant.CITY_NAME);
        cityCode = spUtils.getString(SpConstant.CITY_CODE);
        homeBannerCatePresenter = new HomeBannerCatePresenter(new CateCall());
        sendOrderPresenter = new SendOrderPresenter(new SendOrderCall());
        homeBannerCatePresenter.reqeust();
        seek_bar.setOnSeekBarChangeListener(this);
        getWeeks();
        rv_week_time.setLayoutManager(new LinearLayoutManager(this));
        weekTimes.add(new WeekTimeBean(1, "00:00", "23:00", "周一"));
        weekTimeAdapter = new WeekTimeAdapter(weekTimes);
        rv_week_time.setAdapter(weekTimeAdapter);
        weekTimeAdapter.addChildClickViewIds(R.id.rb_week, R.id.ll_week_time, R.id.ll_week_time_no);
        weekTimeAdapter.setOnItemChildClickListener(new OnItemChildClickListener() {
            @Override
            public void onItemChildClick(@NonNull BaseQuickAdapter adapter, @NonNull View view, int position) {
                if (view.getId() == R.id.rb_week) {
                    showChooseWeek(position);
                } else {
                    showChooseTime(position);
                }
            }
        });
        rb_set_age.setOnCheckedChangeListener((buttonView, isChecked) -> {
            if (isChecked) {
                seek_bar.setProgress(100);
            }
        });
        rl_edit_money.setOnClickListener(v -> {
            String money = et_money.getText().toString().trim();
            int i;
            if (!money.equals("")) {
                int integer = Integer.parseInt(money);
                if (integer > 1) {
                    i = integer - 1;
                    et_money.setText(i + "");
                }
            }
        });
        rl_edit_money_right.setOnClickListener(v -> {
            String money = et_money.getText().toString().trim();
            int i;
            if (!money.equals("")) {
                int integer = Integer.parseInt(money);
                i = integer + 1;
                et_money.setText(i + "");
            }
        });
        rl_choose_skill.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showSkillDialog();
            }
        });
        ll_add_week.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                addWeekTime();
            }
        });
        rg_gender.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if (checkedId == R.id.rb_set_sex) {
                    gender = "0";
                } else if (checkedId == R.id.rb_male) {
                    gender = "1";
                } else {
                    gender = "2";
                }
            }
        });
    }

    private void addWeekTime() {
        if (weekTimes.size() < 7) {
            weekTimes.add(new WeekTimeBean(1, "00:00", "23:00", "周一"));
            weekTimeAdapter.notifyDataSetChanged();
        }
    }

    @OnClick(R.id.tv_send_order)
    public void submitOrder() {
        String money = et_money.getText().toString().trim();
        if (TextUtils.isEmpty(money)) {
            UIUtils.showToastSafe("金额不能为空");
            return;
        }
        if (TextUtils.isEmpty(skill)){
            UIUtils.showToastSafe("请选择发单技能");
            return;
        }
        StringBuilder str = new StringBuilder();
        for (int i = 0; i < weekTimes.size(); i++) {
            if (i == weekTimes.size() - 1) {
                str.append(weekTimes.get(i).getWeek() + "_" + weekTimes.get(i).getStartTime() + "-" + weekTimes.get(i).getEndTime());
            } else {
                str.append(weekTimes.get(i).getWeek() + "_" + weekTimes.get(i).getStartTime() + "-" + weekTimes.get(i).getEndTime());
                str.append(",");
            }
        }
        timeLimit = str.toString();
        sendOrderPresenter.reqeust("Bearer " + token, categoryId, cityCode, cityName, gender, filePath, 0.0, 0.0, content, Double.parseDouble(money), timeLimit, 0);
    }

    private void getWeeks() {
        weeks.add(new WeekTimeBean(1, "", "", "周一"));
        weeks.add(new WeekTimeBean(2, "", "", "周二"));
        weeks.add(new WeekTimeBean(3, "", "", "周三"));
        weeks.add(new WeekTimeBean(4, "", "", "周四"));
        weeks.add(new WeekTimeBean(5, "", "", "周五"));
        weeks.add(new WeekTimeBean(6, "", "", "周六"));
        weeks.add(new WeekTimeBean(7, "", "", "周日"));
    }

    private void showChooseWeek(int position) {
        ArrayList<String> list = new ArrayList<>();
        for (int i = 0; i < weeks.size(); i++) {
            list.add(weeks.get(i).getWeekName());
        }
        SinglePicker<String> picker = new SinglePicker<>(this, list);
        picker.setCanLoop(false);//不禁用循环
        picker.setLineVisible(true);
        picker.setTextSize(16);
        picker.setSelectedIndex(0);
        picker.setItemWidth(200);
        picker.setOuterLabelEnable(true);
        picker.setGravity(Gravity.BOTTOM);
        picker.setLineColor(ContextCompat.getColor(this, R.color.color_EEEEEE));
        picker.setSelectedTextColor(ContextCompat.getColor(this, R.color.text_dark_gray));//前四位值是透明度
        picker.setUnSelectedTextColor(ContextCompat.getColor(this, R.color.color_9C9DA1));
        picker.setOnSingleWheelListener((index, item) -> {
            week = index;
            weekName = item;
        });
        picker.setOnItemPickListener((index, item) -> {
            week = index;
            weekName = item;
            weekTimes.get(position).setWeek(week);
            weekTimes.get(position).setWeekName(weekName);
            weekTimeAdapter.notifyDataSetChanged();
        });
        picker.show();
    }

    private void showSkillDialog() {
        ArrayList<String> list = new ArrayList<>();
        if (cates.size() > 0) {
            for (int i = 0; i < cates.size(); i++) {
                list.add(cates.get(i).getCaption());
            }
            SinglePicker<String> picker = new SinglePicker<>(this, list);
            picker.setCanLoop(false);//不禁用循环
            picker.setLineVisible(true);
            picker.setTextSize(16);
            picker.setSelectedIndex(2);
            picker.setItemWidth(200);
            picker.setOuterLabelEnable(true);
            picker.setGravity(Gravity.BOTTOM);
            picker.setLineColor(ContextCompat.getColor(this, R.color.color_EEEEEE));
            picker.setSelectedTextColor(ContextCompat.getColor(this, R.color.text_dark_gray));//前四位值是透明度
            picker.setUnSelectedTextColor(ContextCompat.getColor(this, R.color.color_9C9DA1));
            picker.setOnSingleWheelListener((index, item) -> {
            });
            picker.setOnItemPickListener((index, item) -> {
                skill = item;
                categoryId = cates.get(index).getId();
                tv_skill.setText(skill);
            });
            picker.show();
        }
    }

    private void showChooseTime(int position) {
        LinkagePicker.DataProvider provider = new LinkagePicker.DataProvider() {

            @Override
            public boolean isOnlyTwo() {
                return true;
            }

            @Override
            public List<String> provideFirstData() {
                return Arrays.asList(Constant.times);
            }

            @Override
            public List<String> provideSecondData(int firstIndex) {
                return Arrays.asList(Constant.times);
            }

            @Override
            public List<String> provideThirdData(int firstIndex, int secondIndex) {
                return null;
            }

        };
        LinkagePicker picker = new LinkagePicker(this, provider);
        picker.setCanLoop(false);
        picker.setSelectedIndex(0, 23);
        picker.setGravity(Gravity.BOTTOM);
        picker.setLineColor(ContextCompat.getColor(this, R.color.color_EEEEEE));
        picker.setSelectedTextColor(ContextCompat.getColor(this, R.color.text_dark_gray));//前四位值是透明度
        picker.setUnSelectedTextColor(ContextCompat.getColor(this, R.color.color_9C9DA1));
        picker.setOnMoreWheelListener(new OnMoreWheelListener() {
            @Override
            public void onFirstWheeled(int index, String item) {
                startTime = item;
            }

            @Override
            public void onSecondWheeled(int index, String item) {
                endTime = item;
            }

            @Override
            public void onThirdWheeled(int index, String item) {

            }
        });
        picker.setOnMoreItemPickListener((OnMoreItemPickListener<String>) (first, second, third) -> {
            startTime = first;
            endTime = second;
            String[] split = startTime.split(":");
            String[] split1 = endTime.split(":");
            String a = split[0];
            String b = split1[0];
            int i = Integer.parseInt(a);
            int i1 = Integer.parseInt(b);
            if (i > i1) {
                UIUtils.showToastSafe("开始时间不能超过结束时间，请重新选择");
            } else {
                weekTimes.get(position).setStartTime(startTime);
                weekTimes.get(position).setEndTime(endTime);
                weekTimeAdapter.notifyDataSetChanged();
            }
        });
        picker.show();
    }

    class CateCall implements DataCall<HomeBannerCate> {

        @Override
        public void success(HomeBannerCate data, Object... args) {
            List<HomeBannerCate.CategoryDTO> category = data.getCategory();
            cates.clear();
            cates.addAll(category);
        }

        @Override
        public void fail(ApiException e, Object... args) {
        }

    }

    class SendOrderCall implements DataCall<String> {

        @Override
        public void success(String data, Object... args) {
            UIUtils.showToastSafe("发布成功");
            finish();
        }

        @Override
        public void fail(ApiException e, Object... args) {
            UIUtils.showToastSafe(e.getDisplayMessage());
        }

    }

    @Override
    protected void destoryData() {

    }

    @Override
    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
        chooseAge = mixAge + progress;
        tv_max.setText(chooseAge + "");
        if (chooseAge < maxAge) {
            rb_set_age.setChecked(false);
        } else {
            rb_set_age.setChecked(true);
        }
    }

    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {

    }

    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {

    }
}
